package com.lagou.edu.service.impl;

import com.lagou.edu.dao.TokenDao;
import com.lagou.edu.pojo.Token;
import com.lagou.edu.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.Optional;

@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private TokenDao tokenDao;

    @Override
    public String createToken(String email, String password) {
        // 简单使用base64对用户名和密码编码作为token
        Base64.Encoder encoder = Base64.getEncoder();
        String encodeToString = encoder.encodeToString((email + password).getBytes());
        return encodeToString;
    }

    @Override
    public void saveToken(String email, String tokenStr) {
        Token token = new Token();
        token.setEmail(email);
        token.setToken(tokenStr);
        tokenDao.save(token);
    }

    @Override
    public String getEmailInfoByToken(String tokenStr) {
        Token token = new Token();
        token.setToken(tokenStr);
        Example<Token> example = Example.of(token);
        Optional<Token> optional =tokenDao.findOne(example);
        if(optional.isPresent()){
            return optional.get().getEmail() ;
        }else{
            return null;
        }
    }

    @Override
    public boolean isRegistered(String email) {
        Token token = new Token();
        token.setEmail(email);
        Example<Token> example = Example.of(token);
        Optional<Token> optional = tokenDao.findOne(example);
        if (optional.isPresent()) {
            return true;
        }
        return false;

    }

    @Override
    public void register(String email, String password) {
        String tokenStr = createToken(email, password);

        Token token = new Token();
        token.setEmail(email);
        token.setToken(tokenStr);
        tokenDao.save(token);
    }

    @Override
    public boolean validate(String email, String password) {
        String tokenStr = createToken(email, password);

        Token user = new Token();
        user.setEmail(email);
        user.setToken(tokenStr);
        Example<Token> example = Example.of(user);
        Optional<Token> optional = tokenDao.findOne(example);
        if (optional.isPresent()) {
            return true;
        }
        return false;
    }

}
